package cn.k7g.alloy.utils;

import cn.k7g.alloy.exception.PasswordInvalidException;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author victor-wu
 * @date 2024/4/9 上午11:36
 */


public class PasswordUtil {
    /**
     * 默认密码最低长度
     */
    public static int PASSWORD_MIN_LENGTH = 8;

    /**
     * 密码强度
     */
    public static int PASSWORD_STRONG_LEVEL = 3;

    public static void assertValidPassword(String newPassword) {
        if (StringUtils.isBlank(newPassword)) {
            // java 国际化提示消息，password.not.blank, 怎么写

            throw new PasswordInvalidException("密码不能为空");
        }
        if (newPassword.indexOf(" ") != -1) {
            throw new PasswordInvalidException("密码不能包含空格");
        }
        String msg = "密码必须包含数字，大小写字母，符号任意三种且长度不能小于" + PASSWORD_MIN_LENGTH + "位";
        if (org.apache.commons.lang3.StringUtils.length(newPassword) < PASSWORD_MIN_LENGTH) {
            throw new PasswordInvalidException(msg);
        }
        int r = 0;
        for (int i = 0; i < newPassword.length(); i++) {
            char c = newPassword.charAt(i);
            if (c >= 'a' && c <= 'z') {
                r |= 1;
            } else if (c >= 'A' && c <= 'Z') {
                r |= 2;
            } else if (c >= '0' && c <= '9') {
                r |= 4;
            } else {
                r |= 8;
            }
            int count = 0;
            for (int j = 0; j <= PASSWORD_STRONG_LEVEL; j++) {
                if ((r & (1 << j)) != 0) {
                    count++;
                }
            }
            if (count >= 3) {
                return;
            }
        }
        throw new PasswordInvalidException(msg);
    }
}
